import { exec } from 'child_process';
import { promisify } from 'util';
import os from 'os';

const execAsync = promisify(exec);

/**
 * 代理状态管理器
 * 负责检测和验证系统代理状态
 */
export class ProxyStatusManager {
  constructor(proxyHost = 'localhost', proxyPort = 12300) {
    this.platform = os.platform();
    this.proxyHost = proxyHost;
    this.proxyPort = proxyPort;
    this.COMMAND_TIMEOUT = 10000; // 10秒
  }

  /**
   * 获取当前代理状态
   */
  async getProxyStatus() {
    try {
      if (this.platform === 'win32') {
        return await this.getWindowsProxyStatus();
      } else if (this.platform === 'darwin') {
        return await this.getMacOSProxyStatus();
      } else {
        throw new Error('不支持的操作系统');
      }
    } catch (error) {
      console.error('❌ 获取代理状态失败:', error.message);
      return {
        enabled: false,
        server: null,
        isOurs: false,
        error: error.message
      };
    }
  }

  /**
   * 获取Windows代理状态
   */
  async getWindowsProxyStatus() {
    try {
      const queryCommands = [
        'reg query "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable',
        'reg query "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyServer'
      ];

      const results = await Promise.all(
        queryCommands.map(cmd => this.executeWithTimeout(cmd).catch(err => ''))
      );

      const proxyEnable = results[0];
      const proxyServer = results[1];

      // 解析ProxyEnable
      const enableMatch = proxyEnable.match(/ProxyEnable\s+REG_DWORD\s+(0x[0-9a-fA-F]+|\d+)/);
      const enabled = enableMatch ? parseInt(enableMatch[1]) === 1 : false;

      // 解析ProxyServer
      const serverMatch = proxyServer.match(/ProxyServer\s+REG_SZ\s+(.+)/);
      const server = serverMatch ? serverMatch[1].trim() : null;

      // 检查是否是我们的代理
      const isOurs = server === `${this.proxyHost}:${this.proxyPort}`;

      return {
        enabled,
        server,
        isOurs,
        platform: 'win32'
      };

    } catch (error) {
      console.error('❌ 获取Windows代理状态失败:', error.message);
      return {
        enabled: false,
        server: null,
        isOurs: false,
        error: error.message
      };
    }
  }

  /**
   * 获取macOS代理状态
   */
  async getMacOSProxyStatus() {
    try {
      const networkServices = await this.getMacOSNetworkServices();
      const status = {
        enabled: false,
        server: null,
        isOurs: false,
        platform: 'darwin',
        services: {}
      };

      for (const service of networkServices) {
        try {
          const proxyInfo = await this.getMacOSServiceProxyInfo(service);
          status.services[service] = proxyInfo;

          if (proxyInfo.enabled) {
            status.enabled = true;
            status.server = `${proxyInfo.server}:${proxyInfo.port}`;
            
            if (proxyInfo.server === this.proxyHost && 
                proxyInfo.port === this.proxyPort.toString()) {
              status.isOurs = true;
            }
          }
        } catch (error) {
          console.warn(`⚠️ 获取服务 ${service} 代理信息失败:`, error.message);
        }
      }

      return status;

    } catch (error) {
      console.error('❌ 获取macOS代理状态失败:', error.message);
      return {
        enabled: false,
        server: null,
        isOurs: false,
        error: error.message
      };
    }
  }

  /**
   * 获取macOS网络服务列表
   */
  async getMacOSNetworkServices() {
    const output = await this.executeWithTimeout(
      'networksetup -listallnetworkservices'
    );
    
    return output
      .split('\n')
      .slice(1) // 跳过第一行标题
      .map(line => line.trim())
      .filter(line => line && !line.startsWith('*'));
  }

  /**
   * 获取macOS特定服务的代理信息
   */
  async getMacOSServiceProxyInfo(service) {
    const output = await this.executeWithTimeout(
      `networksetup -getwebproxy "${service}"`
    );

    const lines = output.split('\n');
    const info = {
      enabled: false,
      server: null,
      port: null
    };

    for (const line of lines) {
      if (line.includes('Enabled: Yes')) {
        info.enabled = true;
      } else if (line.includes('Server: ')) {
        info.server = line.split('Server: ')[1].trim();
      } else if (line.includes('Port: ')) {
        info.port = line.split('Port: ')[1].trim();
      }
    }

    return info;
  }

  /**
   * 验证代理恢复结果
   */
  async verifyProxyRestore() {
    try {
      console.log('🔍 验证代理恢复结果...');
      
      // 等待设置生效
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      const newStatus = await this.getProxyStatus();
      console.log('🔍 验证结果:', newStatus);
      
      // 检查代理是否已禁用或不再是我们的代理
      const success = !newStatus.enabled || !newStatus.isOurs;
      
      if (success) {
        console.log('✅ 代理恢复验证成功');
      } else {
        console.error('❌ 代理恢复验证失败');
        console.log('💡 当前代理仍然启用且指向我们的服务器');
      }
      
      return success;
      
    } catch (error) {
      console.error('❌ 验证代理恢复失败:', error.message);
      return false;
    }
  }

  /**
   * 同步获取代理状态
   */
  getProxyStatusSync() {
    try {
      if (this.platform === 'win32') {
        return this.getWindowsProxyStatusSync();
      } else if (this.platform === 'darwin') {
        return this.getMacOSProxyStatusSync();
      } else {
        throw new Error('不支持的操作系统');
      }
    } catch (error) {
      console.error('❌ 同步获取代理状态失败:', error.message);
      return {
        enabled: false,
        server: null,
        isOurs: false,
        error: error.message
      };
    }
  }

  /**
   * 同步获取Windows代理状态
   */
  getWindowsProxyStatusSync() {
    try {
      const { execSync } = require('child_process');

      const proxyEnable = execSync(
        'reg query "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable',
        { encoding: 'utf8', timeout: 5000 }
      );

      const proxyServer = execSync(
        'reg query "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyServer',
        { encoding: 'utf8', timeout: 5000 }
      ).catch(() => '');

      // 解析结果
      const enableMatch = proxyEnable.match(/ProxyEnable\s+REG_DWORD\s+(0x[0-9a-fA-F]+|\d+)/);
      const enabled = enableMatch ? parseInt(enableMatch[1]) === 1 : false;

      const serverMatch = proxyServer.match(/ProxyServer\s+REG_SZ\s+(.+)/);
      const server = serverMatch ? serverMatch[1].trim() : null;

      const isOurs = server === `${this.proxyHost}:${this.proxyPort}`;

      return { enabled, server, isOurs, platform: 'win32' };

    } catch (error) {
      return {
        enabled: false,
        server: null,
        isOurs: false,
        error: error.message
      };
    }
  }

  /**
   * 同步获取macOS代理状态  
   */
  getMacOSProxyStatusSync() {
    try {
      const { execSync } = require('child_process');
      
      // 获取网络服务列表
      const servicesOutput = execSync('networksetup -listallnetworkservices', { 
        encoding: 'utf8', 
        timeout: 5000 
      });
      
      const services = servicesOutput
        .split('\n')
        .slice(1)
        .map(line => line.trim())
        .filter(line => line && !line.startsWith('*'));

      const status = {
        enabled: false,
        server: null,
        isOurs: false,
        platform: 'darwin',
        services: {}
      };

      for (const service of services) {
        try {
          const proxyOutput = execSync(`networksetup -getwebproxy "${service}"`, {
            encoding: 'utf8',
            timeout: 3000
          });

          const proxyInfo = this.parseMacOSProxyOutput(proxyOutput);
          status.services[service] = proxyInfo;

          if (proxyInfo.enabled) {
            status.enabled = true;
            status.server = `${proxyInfo.server}:${proxyInfo.port}`;
            
            if (proxyInfo.server === this.proxyHost && 
                proxyInfo.port === this.proxyPort.toString()) {
              status.isOurs = true;
            }
          }
        } catch (error) {
          // 忽略单个服务的错误
        }
      }

      return status;

    } catch (error) {
      return {
        enabled: false,
        server: null,
        isOurs: false,
        error: error.message
      };
    }
  }

  /**
   * 解析macOS代理输出
   */
  parseMacOSProxyOutput(output) {
    const lines = output.split('\n');
    const info = {
      enabled: false,
      server: null,
      port: null
    };

    for (const line of lines) {
      if (line.includes('Enabled: Yes')) {
        info.enabled = true;
      } else if (line.includes('Server: ')) {
        info.server = line.split('Server: ')[1].trim();
      } else if (line.includes('Port: ')) {
        info.port = line.split('Port: ')[1].trim();
      }
    }

    return info;
  }

  /**
   * 同步验证代理恢复结果
   */
  verifyProxyRestoreSync() {
    try {
      console.log('🔍 同步验证代理恢复结果...');
      
      const newStatus = this.getProxyStatusSync();
      console.log('🔍 验证结果:', newStatus);
      
      const success = !newStatus.enabled || !newStatus.isOurs;
      
      if (success) {
        console.log('✅ 代理恢复验证成功');
      } else {
        console.error('❌ 代理恢复验证失败');
      }
      
      return success;
      
    } catch (error) {
      console.error('❌ 同步验证代理恢复失败:', error.message);
      return false;
    }
  }

  /**
   * 执行命令（带超时）
   */
  async executeWithTimeout(command, timeout = this.COMMAND_TIMEOUT) {
    try {
      const { stdout } = await execAsync(command, {
        timeout,
        encoding: 'utf8'
      });
      return stdout.trim();
    } catch (error) {
      throw new Error(`命令执行失败: ${command} - ${error.message}`);
    }
  }
} 